import React, { useRef, useState, useEffect } from 'react';
import { Button, Row, Col, Input,Popconfirm, message  } from 'antd';
const { Search } = Input
import ProTable from '@ant-design/pro-table';
import { FormattedMessage, useIntl } from "umi";
import { paginationQueryDictData,deleteDictData } from '../../../services/dictData';
import { PlusOutlined,EditTwoTone,DeleteFilled } from '@ant-design/icons'
import { ROW_ID_KEY, OPERATE_ADD, OPERATE_EDIT } from '../../../constants';
import styles from '../index.less'
import DictDataOperatePanel from './DictDataOperatePanel';
const PaginationQueryDictDataTable = ({ dictTypeUnCode }) => {
  const intl = useIntl();
  const [context, setContext] = useState() //模糊搜索关键词
  const [showPanel, setShowPanel] = useState() //字典值新增/编辑面板显隐标识
  const [operateType,setOperateType] = useState()
  const [paginationData,setPaginationData] = useState({'current':1,'pageSize':10,'total':0})
  const [dictData,setDictData]=useState({dictTypeUnCode:dictTypeUnCode})
  const ref = useRef()
  // 获取数据
  async function getData(params) {
    params.dictTypeUnCode = dictTypeUnCode;
    params.context = context
    let res = await paginationQueryDictData(params);
    if (res.success) {
      let resData = {
        ...res?.data,
        data: res?.data?.records
      }
      setContext()
      setPaginationData({'current':resData?.current,'pageSize':resData?.pageSize,'total':resData?.total})
      return resData
    }
  }
  //监控dictTypeUnCode
  useEffect(() => {
    if(dictTypeUnCode === undefined){
      return; 
    }
    setDictData({...dictData,dictTypeUnCode:dictTypeUnCode})
    setPaginationData({'current':1,'pageSize':10,'total':0})
    ref.current.reload();
  }, dictTypeUnCode)

  let closePanel = () => {
    setShowPanel(false)
    ref.current.reload();
  }
  let openPanel = ()=>{
    setOperateType(OPERATE_ADD)
    setShowPanel(true)
  }
  let onSearch = (value) => {
    setContext(value)
    ref.current.reload();
  }
  const onEdit=(row)=>{
    setDictData(row)
    setShowPanel(true)
    setOperateType(OPERATE_EDIT)
  }
  const onDelete=async(row)=>{
    await deleteDictData(row?.unCode).then(res=>{
      if(res.success){
        message.success(res.msg)
        ref.current.reload();
      }
    })
  }
  //TODO 将其抽离成一个外部方法
  let onPaginationChange=(current,pageSize)=>{
    setPaginationData({...paginationData,current,pageSize})
    getData({dictTypeUnCode:dictTypeUnCode,context:context,current,current,pageSize,pageSize})
  }
  // columns
  const columns = [
    {
      title: '编码',
      dataIndex: 'code',
      width: 70,
      ellipsis: true,
    },
    // {
    //   title: formatMessage({ id: 'demand.history.type' }),
    //   dataIndex: 'tableData',
    //   valueEnum: tableData,//这一列是后端返回的数据，目前还没有找到好的方法可以直接让搜索框和table展示数据一致，只能外加一个valueEnum让table展示正确数据
    //   request: async () => getData(),
    // },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '字典值',
      dataIndex: 'value',
      ellipsis: true,
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      hideInSearch: true,
      width: 80,
      valueEnum: {
        'Y': {
          status: "Success", text: '是'
        },
        'N': {
          status: 'Error', text: '否'
        }
      }
    },
    {
      title: '是否启用',
      dataIndex: 'statusFlag',
      hideInSearch: true,
      valueEnum: {
        'ENABLED': {
          status: "Success", text: '启用'
        },
        'DISABLED': {
          status: 'Error', text: '禁用'
        }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInSearch: true,
    },
    {
      title: '最后更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      hideInSearch: true,
      width:80,
      dataIndex: { ROW_ID_KEY },
      render: (text, row) => [
       
        <Button type="text" key={'edit'} shape="circle" size='small' onClick={()=>{onEdit(row)}} icon={<EditTwoTone />}/>,
        <Popconfirm
          key={'delete'} 
          title={intl.formatMessage({
            id: 'pages.Popconfirm.title',
            defaultMessage: '确认删除'
          })}
          toolBar
          description={intl.formatMessage({
            id: 'pages.Popconfirm.description',
            defaultMessage: '是否删除该条记录？'
          })}
          onConfirm={()=>{onDelete(row)}}
          okText={intl.formatMessage({
            id: 'pages.Popconfirm.okText',
            defaultMessage: '确认'
          })}
          cancelText={intl.formatMessage({
            id: 'pages.Popconfirm.cancelText',
            defaultMessage: '取消'
          })}>
            <Button type="text" danger shape="circle" size='small' icon={<DeleteFilled />}/>
        </Popconfirm>,
        
      ],
    },
  ];

  return (
    <>
      {showPanel && <DictDataOperatePanel operateType={operateType} dictDate={dictData} closePanel={closePanel} />}
      <ProTable
        actionRef={ref}
        className={styles.dict_data_table}
        search={false}
        options={{ fullScreen: false, reload: true, density: true, setting: true }}
        columns={columns}
        request={async (params = {}) => getData(params)
        }
        pagination={{
          pageSize: paginationData.pageSize,
          total: paginationData.total,
          current: paginationData.current,
          showSizeChanger: true,
          onChange: onPaginationChange
          }}
        rowKey={ROW_ID_KEY}
        dateFormatter="string"
        headerTitle={intl.formatMessage({
          id: 'app.dictType.table.title',
          defaultMessage: '字典值管理'
        })}
        toolBarRender={() => [

          <>
            <Row align='middle' justify='space-between' style={{ width: '400px' }}>
              <Col span={19}>
                <Search
                  style={{ width: '290px' }}
                  placeholder={intl.formatMessage({
                    id: 'app.dictData.table.toolBar.search.placeholder',
                    defaultMessage: '请输入字典值编码、值、标签关键词'
                  })}
                  onSearch={onSearch}
                />
              </Col>
              <Col span={5}>
                <Button key="3" type="primary" onClick={openPanel}>
                  <PlusOutlined />
                  <FormattedMessage id='component.button.add' />
                </Button>
              </Col>
            </Row>

          </>,
        ]}
      />
    </>
  );
}
export default PaginationQueryDictDataTable;